﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using RN.ERP.Web.ModelService;
using Newtonsoft.Json;
using Fly.Common.Linq;
using System.Web.Services;
using RN.ERP.Web.BasicService;
using RN.ERP.Web.PersonService;
using Fly.Common.WorkFlow;
using Telerik.Web.UI;
using System.Configuration;

namespace RN.ERP.Web.Enterprise
{
    public partial class EnterpriseCorpInfo14 : BasePage
    {
        /// <summary>
        /// 需要显示安全许可证的企业
        /// </summary>
        public string SecurityIDS
        {
            get
            {
                string ids = "2501";
                if (ConfigurationManager.AppSettings["SecurityIDS"] != null)
                {
                    ids = ConfigurationManager.AppSettings["SecurityIDS"].ToString();
                }
                return ids;
            }
        }
        private EnterpriseService.EnterpriseServiceClient enterpriseServiceClient = new EnterpriseService.EnterpriseServiceClient();
        private BasicService.BasicServiceClient basicServiceClient = new BasicService.BasicServiceClient();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                InitPage();
                BindDropDown();
                InitData();
                BindMarket();
                InitCorpFlowStatus();
                IsCheckShowEmp();
            }
        }
        protected void RadGridLog_NeedDataSource(object source, GridNeedDataSourceEventArgs e)
        {
            PersonServiceClient client = new PersonServiceClient();
            string corpUserGuid = GetCorpUserGuid();
            var logsCount = client.GetUserLogCount(corpUserGuid, UserInfo.RoleType, UserInfo.CurrentArea);
            var logs = JsonConvert.DeserializeObject<List<User_Log>>(client.GetUserLogList(RadGridLog.CurrentPageIndex + 1, RadGridLog.PageSize, corpUserGuid, UserInfo.RoleType, UserInfo.CurrentArea));
            RadGridLog.AllowCustomPaging = true;
            RadGridLog.VirtualItemCount = logsCount;
            RadGridLog.DataSource = logs;
        }
        /// <summary>
        /// 根据用户权限、角色初始化界面显示
        /// </summary>
        private void InitPage()
        {
            ////获取企业信息，登陆账户与企业不一致
            string corpUserGuid = GetCorpUserGuid();
            //begin是否可上传图片2013-12-4
            if (ConfigurationManager.AppSettings["CanUploadPic"] != null)
            {
                string CanUploadPic = ConfigurationManager.AppSettings["CanUploadPic"].ToString();
                if (CanUploadPic != "0" && UserInfo.RoleType == "User" && corpUserGuid == UserInfo.CorpUserGuid)
                {
                    //除管理端显示上传按钮
                    hdnCanUploadPic.Value = "1";
                }
            }//end
            ////企业类型暂时不允许修改
            DDLCorpUserType.Disabled = true;
            var currentAreaCode = UserInfo.CurrentArea;

            var corpInfo = GetCompanyinfo(corpUserGuid);
            ucShenHeState.ClassId = corpInfo.classID == null ? "" : Convert.ToString(corpInfo.classID);
            ltrEmbranchmentTitle.Text = "外地入" + GetAreaTitle(UserInfo.CurrentArea);
            ltrEmbranchmentLicenceCode.Text = "外地入" + GetAreaTitle(UserInfo.CurrentArea) + "备案编号";
            if (currentAreaCode.Length >= 2 && corpInfo.AreaCode.StartsWith(currentAreaCode.Substring(0, 2)))
            {
                ////企业注册地为当前市场范围则不显示外地准入信息
                divEmbranchment.Visible = false;
                ////2014-2-17 补充外地准入证明扫描件 毛凯
                imgWDZR.Visible = false;
            }

            string ids = SecurityIDS;
            string[] array = ids.Split(',');

            if (array.Contains(corpInfo.classID.ToString()))
            {
                divSecurityCode.Visible = true;
                imgCorpAq.Visible = true;
            }
            else
            {
                divSecurityCode.Visible = false;
                imgCorpAq.Visible = false;
            }
            var Embranchments = enterpriseServiceClient.GetCorpEmbranchments(JsonConvert.SerializeObject(corpInfo));
            var CorpEmbranchments = JsonConvert.DeserializeObject<IList<Tb_Corp_Embranchment>>(Embranchments);
            OperationResult flowEditResult = new OperationResult();
            flowEditResult = JsonConvert.DeserializeObject<OperationResult>(enterpriseServiceClient.CheckCorpEditStatus(corpInfo.CorpUserGuid.ToString(), ""));
            var flowCode = GetEmbranchmentFlow(currentAreaCode);
            var currentEmbranchEditResult = JsonConvert.DeserializeObject<FlowResult>(basicServiceClient.GetNextFlowCode(UserInfo.RoleId, "", currentAreaCode, corpInfo.classID.ToString(), flowCode, BasicService.OptType.Edit));
            var flowPostResult = JsonConvert.DeserializeObject<FlowResult>(basicServiceClient.GetNextFlowCode(UserInfo.RoleId, "", currentAreaCode, corpInfo.classID.ToString(), flowCode, BasicService.OptType.Post));
            var flowAuditResult = JsonConvert.DeserializeObject<FlowResult>(basicServiceClient.GetNextFlowCode(UserInfo.RoleId, "", currentAreaCode, corpInfo.classID.ToString(), flowCode, BasicService.OptType.Audit));
            var flowRejectResult = JsonConvert.DeserializeObject<FlowResult>(basicServiceClient.GetNextFlowCode(UserInfo.RoleId, "", currentAreaCode, corpInfo.classID.ToString(), flowCode, BasicService.OptType.Reject));
            var flowCancelPostResult = JsonConvert.DeserializeObject<FlowResult>(basicServiceClient.GetNextFlowCode(UserInfo.RoleId, "", currentAreaCode, corpInfo.classID.ToString(), flowCode, BasicService.OptType.CancelPost));
            hdnCurrentEmbranchEditResult.Value = currentEmbranchEditResult.Result ? "0" : "1";
            bool notSelfCorp = true;
            if (UserInfo.RoleType == "User" && corpUserGuid == UserInfo.CorpUserGuid)
            {
                notSelfCorp = false;
            }
            if (!flowEditResult.Result || UserInfo.RoleType == "Manager")
            {
                ////不可编辑
                divSave.Visible = false;
                hdnEditModel.Value = "1";
                ucArea.Enable = false;
                ////当前市场允许编辑，分支机构信息可编辑保存
                if (currentEmbranchEditResult.Result && !corpInfo.AreaCode.StartsWith(currentAreaCode))
                {
                    divSave.Visible = true;
                    hdnCurrentEmbranchEditModel.Value = "0";
                }
                else
                {
                    divSave.Visible = false;
                    hdnCurrentEmbranchEditModel.Value = "1";
                }
            }
            else
            {
                divSave.Visible = true;
                hdnEditModel.Value = "0";
                ucArea.Enable = true;
            }

            if (flowPostResult.Result)
            {
                divPost.Visible = true;
                divCancelPost.Visible = false;
            }
            else if (flowCancelPostResult.Result)
            {
                divPost.Visible = false;
                divCancelPost.Visible = true;
            }
            else
            {
                divPost.Visible = false;
                divCancelPost.Visible = false;
            }
            if (!flowAuditResult.Result && !flowRejectResult.Result)
            {
                ////不可审核
                divAudit.Visible = false;
            }
            else
            {
                divAudit.Visible = true;
            }
            ////企业端可查看其他企业信息，对其他企业信息不能做任何操作
            if (UserInfo.RoleType == "User" && notSelfCorp)
            {
                divSave.Visible = false;
                hdnEditModel.Value = "1";
                ucArea.Enable = false;
                hdnCurrentEmbranchEditModel.Value = "0";
                divPost.Visible = false;
                divAudit.Visible = false;
                hdnCurrentEmbranchEditResult.Value = "1";////管理人员操作按钮屏蔽
            }
            if (UserInfo.RoleType == "User")
            {
                tishi.Visible = true;
            }
            else
            {
                tishi.Visible = false;
                personListDiv.Visible = true;
            }
            if (Application[ApplicationConstant.APPLICATION_ID].ToString() == "101")
            {
                imageLand.Visible = true;
            }
        }

        private void InitData()
        {
            var currentAreaCode = UserInfo.CurrentArea;
            ////获取企业信息，登陆账户与企业不一致
            string corpUserGuid = GetCorpUserGuid();
            var corpInfo = GetCompanyinfo(corpUserGuid);
            var khCorpInfo = JsonConvert.DeserializeObject<Kh_CorpTable>(enterpriseServiceClient.GetCorpSecurity(corpUserGuid, currentAreaCode));
            var embrabchMent = JsonConvert.DeserializeObject<List<Tb_Corp_Embranchment>>(enterpriseServiceClient.GetCorpEmbranchments(JsonConvert.SerializeObject(corpInfo)));
            hdnCorpUserguid.Value = corpInfo.CorpUserGuid.ToString();
            txtCorpName.Value = corpInfo.CorpName;
            txtAddress.Value = corpInfo.Address;
            txtBussinessArea.Text = UtilitiesTool.ToTXT(corpInfo.BussinessArea);
            txtBussinessNum.Value = corpInfo.BussinessNum;
            txtEmail.Text = corpInfo.Email;
            txtFax.Text = corpInfo.Fax;
            txtIntroduction.Text = UtilitiesTool.ToTXT(corpInfo.Introduction);
            txtLinkMan.Value = corpInfo.LinkMan1;
            txtLinkManCertificateNumber.Text = corpInfo.CertificateNumber;
            txtNetAddress.Text = corpInfo.NetAddress;
            txtOrginazationCode.Value = corpInfo.OrginazationCode;
            DateTime found = DateTime.Now;
            if (DateTime.TryParse(corpInfo.FoundTime, out found))
            {
                txtFoundTime.Value = found.ToShortDateString();
            }
            else
            {
                txtFoundTime.Value = "";
            }
            txtRegisterMoney.Value = corpInfo.RegisterMoney;
            txtTel.Value = corpInfo.Tel;
            txtZipCode.Text = corpInfo.ZipCode;
            ucArea.AreaCode = corpInfo.AreaCode;
            txtBankName.Text = corpInfo.BankName;
            txtBankAccNo.Text = corpInfo.BankAccNo;
            var role = GetRoleIdByClassId(corpInfo.classID.ToString());
            if (AppID == "101")////为了演示临时处理  20140528  llm
            {
                int? classId = corpInfo.classID;
                if (classId != null && (classId == 25060 || classId == 25010 || classId == 23010 || classId == 300))
                {
                    classId = classId / 10;
                }
                if (classId != null && classId == 2501)
                {
                    role = "15";
                    if (DDLCorpUserType.Items.FindByValue(role) != null)
                    {
                        DDLCorpUserType.Items.FindByValue(role).Text = "建筑施工企业";
                    }
                }else if (classId != null && classId == 2506)
                {
                    role = "15";
                    if (DDLCorpUserType.Items.FindByValue(role) != null)
                    {
                        DDLCorpUserType.Items.FindByValue(role).Text = "建筑装饰企业";
                    }
                }
                else if (classId != null && classId == 2301)
                {
                    role = "15";
                    if (DDLCorpUserType.Items.FindByValue(role) != null)
                    {
                        DDLCorpUserType.Items.FindByValue(role).Text = "门窗企业";
                    }
                }
                else if (classId != null && classId == 30)
                {
                    role = "15";
                    if (DDLCorpUserType.Items.FindByValue(role) != null)
                    {
                        DDLCorpUserType.Items.FindByValue(role).Text = "商砼企业";
                    }
                }
            }
            if (DDLCorpUserType.Items.FindByValue(role) != null)
            {
                DDLCorpUserType.Items.FindByValue(role).Selected = true;
            }
            if (corpInfo.CorpType.HasValue && DDlCorpType.Items.FindByValue(corpInfo.CorpType.ToString()) != null)
            {
                DDlCorpType.Items.FindByValue(corpInfo.CorpType.ToString()).Selected = true;
            }
            if (ddlLinkManCertificateType.Items.FindByValue((corpInfo.CertificateType ?? -1).ToString()) != null)
            {
                ddlLinkManCertificateType.Items.FindByValue((corpInfo.CertificateType ?? -1).ToString()).Selected = true;
            }
            txtQualificationNum.Value = corpInfo.QualificationNum;
            txtLinkManTel.Value = corpInfo.Tel1;
            ////分支机构信息
            hdnEmbranchCorpUserGuid.Value = corpInfo.CorpUserGuid.ToString();
            hdnEmbranchCorpGuid.Value = corpInfo.CorpGuid.ToString();
            hdnEmbranchAreaCode.Value = UserInfo.AreaCode;
            var currentEmbranchment = embrabchMent.Where(e => e.AreaCode.StartsWith(UserInfo.AreaCode)).FirstOrDefault();
            if (currentEmbranchment != null && currentEmbranchment.AreaCode != corpInfo.AreaCode)
            {
                txtEmbranchmentAddress.Text = currentEmbranchment.Address;
                txtEmbranchmentLinkMan.Text = currentEmbranchment.LinkMan;
                txtEmbranchmentLinkTel.Text = currentEmbranchment.LinkTel;
                txtEmbranchmentRemark.Text = currentEmbranchment.Remark;
                txtEmbranchmentTel.Text = currentEmbranchment.Tel;
                txtEmbranchmentLicenceCode.Text = currentEmbranchment.licenceCode;
                txtBranchName.Text = currentEmbranchment.BranchName;
                hdnEmbranchGid.Value = currentEmbranchment.BranchGid.ToString();
            }
            ////安全生产许可证
            hdnkhAreaCode.Value = corpInfo.AreaCode;
            hdnkhCorpUserguid.Value = corpInfo.CorpUserGuid.ToString();
            hdnkhCorpName.Value = corpInfo.CorpName;
            if (khCorpInfo != null)
            {
                txtSecurityCode.Text = khCorpInfo.SafeLicenceNo;
                txtSecurityTitleGetDate.Value = khCorpInfo.LicenceBeginDate.HasValue ? ((DateTime)khCorpInfo.LicenceBeginDate).ToShortDateString() : "";
                txtEndDate.Value = khCorpInfo.LicenceEndDate.HasValue ? ((DateTime)khCorpInfo.LicenceEndDate).ToShortDateString() : "";
            }
            ////ucMarketInfo.CorpUserGuid = corpUserGuid;

            ucShenHeState.AreaCode = UserInfo.CurrentArea;

        }

        private void BindDropDown()
        {
            ////企业类型
            string appCorpUserGuid = Application[ApplicationConstant.APPLICATION_CORPUSERTYPE] != null ? Application[ApplicationConstant.APPLICATION_CORPUSERTYPE].ToString() : "";
            var CorpUserType = JsonConvert.DeserializeObject<Dictionary<string, string>>(appCorpUserGuid);
            DDLCorpUserType.DataSource = CorpUserType;
            DDLCorpUserType.DataValueField = "Key";
            DDLCorpUserType.DataTextField = "Value";
            DDLCorpUserType.DataBind();
            DDLCorpUserType.Items.Insert(0, new ListItem("--请选择--", "-1"));
            ////所有权性质
            string appCorpType = Application[ApplicationConstant.APPLICATION_CORPTYPE] != null ? Application[ApplicationConstant.APPLICATION_CORPTYPE].ToString() : "";
            var CorpType = JsonConvert.DeserializeObject<Dictionary<string, string>>(appCorpType);
            DDlCorpType.DataSource = CorpType;
            DDlCorpType.DataValueField = "Key";
            DDlCorpType.DataTextField = "Value";
            DDlCorpType.DataBind();
            DDlCorpType.Items.Insert(0, new ListItem("--请选择--", "-1"));
            ////证件类型
            string appCertificate = Application[ApplicationConstant.APPLICATION_CERTIFICATETYPE] != null ? Application[ApplicationConstant.APPLICATION_CERTIFICATETYPE].ToString() : "";
            var CertificateType = JsonConvert.DeserializeObject<Dictionary<string, string>>(appCertificate);
            ddlLinkManCertificateType.DataSource = CertificateType;
            ddlLinkManCertificateType.DataValueField = "Key";
            ddlLinkManCertificateType.DataTextField = "Value";
            ddlLinkManCertificateType.DataBind();
            ddlLinkManCertificateType.Items.Insert(0, new ListItem("--请选择--", "-1"));
        }

        public string GetAreaTitle(object areaCode)
        {
            string title = "";
            if (areaCode != null)
            {
                string code = areaCode.ToString();
                if (code.Length >= 2)
                {
                    string appArea = Application[ApplicationConstant.APPLICATION_AREA] != null ? Application[ApplicationConstant.APPLICATION_AREA].ToString() : "";
                    var areaInfos = JsonConvert.DeserializeObject<List<a_AreaInfo>>(appArea);
                    var currentArea = areaInfos.Where(a => code.StartsWith(a.Code)).FirstOrDefault();
                    title = currentArea == null ? "" : currentArea.Title;
                }
            }
            return title;
        }

        public string GetSubAreaTitle(object areaCode)
        {

            string title = "";
            if (areaCode != null)
            {
                string code = areaCode.ToString();
                if (code.Length > 2)
                {
                    var subAreaInfos = JsonConvert.DeserializeObject<List<ModelService.a_AreaSubInfo>>(basicServiceClient.GetQu(code.Substring(0, 2)));
                    var currentSubArea = subAreaInfos.Where(a => a.SortCode == areaCode).FirstOrDefault();
                    title = currentSubArea == null ? "" : currentSubArea.Title;
                }
            }
            return title;
        }

        public void BindMarket()
        {
            string corpUserGuid = GetCorpUserGuid();
            var corpInfo = GetCompanyinfo(corpUserGuid);
            if (corpInfo == null)
            {
                return;
            }
            var flow = JsonConvert.DeserializeObject<Tb_FlowCode>(enterpriseServiceClient.GetCorpFlowCode(JsonConvert.SerializeObject(corpInfo), UserInfo.CurrentArea));
            string flowCode = string.Empty;
            if (flow != null)
            {
                flowCode = string.IsNullOrEmpty(flow.FlowCode) ? "" : flow.FlowCode;
            }
            ltrCurrentMarketFlow.Text = basicServiceClient.GetFlowCodeTitle(UserInfo.CurrentArea, corpInfo.classID.ToString(), flowCode);
            ucShenHeState.FlowCode = flowCode;
        }

        public string GetEmbranchmentFlow(object areaCode)
        {
            string flowTitle = "";
            if (areaCode == null)
            {
                return flowTitle;
            }
            string code = areaCode.ToString();
            Tb_Corp_CompanyInfo corpInfo = new Tb_Corp_CompanyInfo();
            corpInfo.CorpUserGuid = Guid.Parse(GetCorpUserGuid());
            var flow = JsonConvert.DeserializeObject<Tb_FlowCode>(enterpriseServiceClient.GetCorpFlowCode(JsonConvert.SerializeObject(corpInfo), code));
            if (flow != null)
            {
                flowTitle = string.IsNullOrEmpty(flow.FlowCode) ? "" : flow.FlowCode;
            }
            return flowTitle;
        }

        private Tb_Corp_CompanyInfo GetCompanyinfo(string corpUserGuid)
        {
            QueryCompanyInfoCondition queryCompanyInfoCondition =
               new QueryCompanyInfoCondition() { CorpUserGuid = new ParameterValue<Guid>() { V = Guid.Parse(corpUserGuid), O = OptEnum.Equal } };
            List<QueryCompanyInfoCondition> queryCompanyInfoList = new List<QueryCompanyInfoCondition>();
            queryCompanyInfoList.Add(queryCompanyInfoCondition);
            var corpInfo = JsonConvert.DeserializeObject<Tb_Corp_CompanyInfo>(enterpriseServiceClient.GetCompanyInfo(JsonConvert.SerializeObject(queryCompanyInfoList), UserInfo.CurrentArea));
            return corpInfo;
        }

        private string GetCorpUserGuid()
        {
            string corpUserGuid = Request.QueryString["corpUserGuid"];
            if (string.IsNullOrEmpty(corpUserGuid))
            {
                corpUserGuid = UserInfo.CorpUserGuid;
            }
            return corpUserGuid;
        }

        private string GetRoleIdByClassId(string classID)
        {
            var roleClassIds = JsonConvert.DeserializeObject<Dictionary<string, string>>(basicServiceClient.GetDictionary("RoleClassId", "", ""));
            var curRoleClass = roleClassIds.FirstOrDefault(r => r.Value == classID);
            if (!string.IsNullOrEmpty(curRoleClass.Key))
            {
                return curRoleClass.Key;
            }
            return "";
        }

        private void InitCorpFlowStatus()
        {
            if (UserInfo.RoleType == "User")
            {
                var status = JsonConvert.DeserializeObject<List<FlowStatus>>(enterpriseServiceClient.GetCorpFlowStatus(GetCorpUserGuid(), UserInfo.CurrentArea));
                rptCorpFlowStatus.DataSource = status;
                rptCorpFlowStatus.DataBind();
            }
        }
        /// <summary>
        /// 是否可以查看管理人员详细信息
        /// </summary>
        protected void IsCheckShowEmp()
        {
            if (UserInfo.CorpUserGuid == GetCorpUserGuid().Trim() || UserInfo.RoleType == "Manager")
            {
                hdnIsShowEmp.Value = "1";//可以
            }
        }
    }
}
